package com.huqing.icu.utils;

import com.huqing.icu.base.LogPlatformDto;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

public class CustomWebUtils {

    private static final String DOMAIN = ".163.com";

    private static final String BACKUP_SUFFIX = "_JF_BACKUP";
    /**
     * 奇遇需要备份的cookie
     */
    private static final List<String> BACKUP_COOKIE = Arrays.asList("NTES_SESS", "NTES_PASSPORT", "NTES_YD_SESS",
            "NTES_YD_PASSPORT", "PHONE_PASSPORT");
    /**
     * 永久cookie
     */
    private static final List<String> PERSISTENT_COOKIE = Arrays.asList("NTES_PASSPORT", "NTES_YD_PASSPORT",
            "PHONE_PASSPORT");


    /**
     * sessionId 的key
     */
    private static final String SESSIONID = "a23-sessionId";

    /**
     * 获取客户端ip地址
     *
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        // 优先从x-forwarded-for获取
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("Proxy-Client-IP");
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("WL-Proxy-Client-IP");
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip))
            ip = request.getRemoteAddr();

        if (StringUtils.isNotBlank(ip) && !"unknown".equalsIgnoreCase(ip))
            return ip.split(",")[0];
        return null;
    }

    public static String getCookieValue(HttpServletRequest request, String key) {
        String value = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (key.equals(cookie.getName())) {
                    if (StringUtils.isNotBlank(cookie.getValue())) {
                        value = cookie.getValue();
                        break;
                    }
                }
            }
        }
        return value;
    }

    /**
     * 登录时获取cookie的方法，主要为解决备份cookie
     *
     * @param request
     * @param response
     * @param key
     * @return
     */
    public static String getLoginCookieValue(HttpServletRequest request, HttpServletResponse response, String key) {
        String value = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                // 如果有备份的，则以备份的cookie为准
                if (BACKUP_COOKIE.contains(key)) {
                    if (getBackupCookieName(key).equals(cookie.getName())) {
                        value = cookie.getValue();
                        deleteCookieValue(request, response, cookie.getName());
                        break;
                    }
                }
                if (key.equals(cookie.getName())) {
                    if (StringUtils.isNotBlank(cookie.getValue())) {
                        value = cookie.getValue();
                    }
                }
            }
        }
        return value;
    }

    public static boolean existsCookie(HttpServletRequest request, String key) {
        boolean exists = false;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (key.equals(cookie.getName())) {
                    exists = true;
                    break;
                }
            }
        }
        return exists;
    }

    /**
     * 备份cookie
     *
     * @param request
     * @param response
     * @param sessionId
     * @return
     */
    public static boolean backupCookie(HttpServletRequest request, HttpServletResponse response, String sessionId) {
        boolean exists = false;
        Cookie[] cookies = request.getCookies();
        cleanBackUpCookie(request, response);// 清除之前的备份
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (!BACKUP_COOKIE.contains(cookie.getName())) {
                    continue;
                }
                Cookie cookieBackup = new Cookie(cookie.getName() + BACKUP_SUFFIX, cookie.getValue());
                cookieBackup.setMaxAge(cookie.getMaxAge());
                if (PERSISTENT_COOKIE.contains(cookie.getName())) {
                    cookieBackup.setMaxAge(Integer.MAX_VALUE);
                }
                cookieBackup.setDomain(DOMAIN);
                cookieBackup.setPath("/");
                cookieBackup.setHttpOnly(cookie.isHttpOnly());
                response.addCookie(cookieBackup);
            }
        }

        //备份sessionId
        backupSessionIdCookie(response, sessionId);
        return exists;
    }

    /**
     * 备份sessionId
     *
     * @param response
     * @param sessionId
     */
    public static void backupSessionIdCookie(HttpServletResponse response, String sessionId) {
        if (sessionId != null) {
            Cookie cookie = new Cookie(SESSIONID, sessionId);
            cookie.setMaxAge(-1);
            cookie.setDomain(DOMAIN);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
    }

    /**
     * 获取对应的备份cookie
     *
     * @param cookieName
     * @return
     */
    public static String getBackupCookieName(String cookieName) {
        if (StringUtils.isNotBlank(cookieName)) {
            return cookieName + BACKUP_SUFFIX;
        }
        return cookieName;
    }


    /**
     * 获取对应的备份cookie
     *
     * @param cookieName
     * @return
     */
    public static String getBackupCookieValue(HttpServletRequest request, String cookieName) {
        if (StringUtils.isNotBlank(cookieName)) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookieName.equals(cookie.getName())) {
                        return cookie.getValue();
                    }
                }
            }
        }
        return null;
    }


    /**
     * 还原cookie
     *
     * @param request
     * @param response
     * @return
     */
    public static boolean restoreCookie(HttpServletRequest request, HttpServletResponse response) {
        boolean exists = false;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().endsWith(BACKUP_SUFFIX)) {
                    String restoreName = cookie.getName().substring(0,
                            cookie.getName().length() - BACKUP_SUFFIX.length());
                    Cookie cookieRestore = new Cookie(restoreName, cookie.getValue());
                    cookieRestore.setMaxAge(cookie.getMaxAge());
                    if (PERSISTENT_COOKIE.contains(cookie.getName())) {
                        cookieRestore.setMaxAge(Integer.MAX_VALUE);
                    }
                    cookieRestore.setDomain(DOMAIN);
                    cookieRestore.setPath("/");
                    cookieRestore.setHttpOnly(cookie.isHttpOnly());
                    response.addCookie(cookieRestore);
                    deleteCookieValue(request, response, cookie.getName());
                }
            }
        }
        return exists;
    }

    public static void cleanBackUpCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().endsWith(BACKUP_SUFFIX)) {
                    deleteCookieValue(request, response, cookie.getName());
                }
            }
        }
    }

    public static void addCookieValue(HttpServletResponse response, String key, String value) {
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(-1);
        cookie.setDomain(DOMAIN);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    public static void addPersistentCookieValue(HttpServletResponse response, String key, String value) {
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(Integer.MAX_VALUE);
        cookie.setDomain(DOMAIN);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    public static void deleteCookieValue(HttpServletRequest request, HttpServletResponse response, String key) {
        boolean exists = existsCookie(request, key);
        if (exists) {
            Cookie cookie = new Cookie(key, null);
            cookie.setMaxAge(0);
            cookie.setDomain(DOMAIN);
            cookie.setPath("/");
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
        }
    }

    /**
     * 获取user-agent
     *
     * @return
     */
    public static String getUserAgent(HttpServletRequest request) {
        String ua = request.getHeader("user-agent");
        if (StringUtils.isNotBlank(ua))
            return ua;
        return StringUtils.defaultIfEmpty(ua, StringUtils.EMPTY);
    }

    /**
     * 来源页面
     *
     * @return
     */
    public static String getRequesReferUrl(HttpServletRequest request) {
        String referer = request.getHeader("referer");
        if (StringUtils.isNotBlank(referer))
            return referer;
        return StringUtils.defaultIfEmpty(referer, StringUtils.EMPTY);
    }

    /**
     * 获取sessionId
     *
     * @param request
     * @return
     */
    public static String getSessionId(HttpServletRequest request) {
        String sessionId = request.getHeader("sessionId");
        if (StringUtils.isNotBlank(sessionId)) {
            return sessionId;
        }
        return StringUtils.defaultIfEmpty(sessionId, StringUtils.EMPTY);
    }

    /**
     * 获取用户类型
     *
     * @param request
     * @return
     */
    public static String getUserType(HttpServletRequest request) {
        String userType = request.getHeader("user-type");
        return StringUtils.defaultIfEmpty(userType, StringUtils.EMPTY);
    }

    /**
     * 获取client-info
     *
     * @param request
     * @return
     */
    public static String getClientInfo(HttpServletRequest request) {
        LogPlatformDto headerClientInfo = HeaderUtil.getHeaderClientInfo(request);
        if (headerClientInfo != null && StringUtils.isNotBlank(headerClientInfo.getOsName())) {
            return headerClientInfo.getOsName();
        }
        return StringUtils.EMPTY;
    }

    public static void addCookieValue(HttpServletResponse response, String key, String value, int seconds) {
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(seconds);
        cookie.setDomain(DOMAIN);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    /**
     * 获取请求头信息
     *
     * @param request
     * @return
     */
    public static LogPlatformDto getHeaderClientInfoAndOrigin(HttpServletRequest request) {
        LogPlatformDto headerClientInfo = HeaderUtil.getHeaderClientInfo(request);
        return headerClientInfo;
    }

    /**
     * 判断投稿来源
     *
     * @param request
     * @return
     */
    public static int judgeSource(HttpServletRequest request) {
        //从请求头中获取设备名称，以便后续判断是APP端还是PC端
        LogPlatformDto logPlatformDto = CustomWebUtils.getHeaderClientInfoAndOrigin(request);
        String osName = logPlatformDto.getOsName();
        String origin = logPlatformDto.getOrigin();

        /*if ("wxMiniProgram".equals(origin)) {
            return ManuscriptsTaskSourceEnum.WX.getCode();
        }
        if ("dyMiniProgram".equals(origin)) {
            return ManuscriptsTaskSourceEnum.DY.getCode();
        }
        if ("windows".equals(osName)) {
            return ManuscriptsTaskSourceEnum.PC.getCode();
        }
        if ("ios".equals(osName) || "android".equals(osName)) {
            return ManuscriptsTaskSourceEnum.APP.getCode();
        }
        return ManuscriptsTaskSourceEnum.APP.getCode();*/
        return 1;
    }
}
